
// table buttons

Refresh.Web.EditorCommands.addCommand({name:'InsertTable',execute:function(ftb,value,src) { Refresh.Web.InsertTableUtility.show(ftb,src);},getValue:Refresh.Web.QueryMethods.alwaysOn });
Refresh.Web.EditorCommands.addCommand({name:'InsertTableRowBefore',execute:function(ftb) { Refresh.Web.TableCommands.insertTableRowBefore(ftb);},getValue:function(ftb) { Refresh.Web.QueryMethods.isInsideTag(ftb,'td'); }});
Refresh.Web.EditorCommands.addCommand({name:'InsertTableRowAfter',execute:function(ftb) { Refresh.Web.TableCommands.insertTableRowAfter(ftb);},getValue:function(ftb) { Refresh.Web.QueryMethods.isInsideTag(ftb,'td'); }});
Refresh.Web.EditorCommands.addCommand({name:'InsertTableColumnBefore',execute:function(ftb) { Refresh.Web.TableCommands.insertTableColumnBefore(ftb);},getValue:function(ftb) { Refresh.Web.QueryMethods.isInsideTag(ftb,'td'); }});
Refresh.Web.EditorCommands.addCommand({name:'InsertTableColumnAfter',execute:function(ftb) { Refresh.Web.TableCommands.insertTableColumnAfter(ftb);},getValue:function(ftb) { Refresh.Web.QueryMethods.isInsideTag(ftb,'td'); }});
Refresh.Web.EditorCommands.addCommand({name:'DeleteTableColumn',execute:function(ftb) { Refresh.Web.TableCommands.deleteTableColumn(ftb);},getValue:function(ftb) { Refresh.Web.QueryMethods.isInsideTag(ftb,'td'); }});
Refresh.Web.EditorCommands.addCommand({name:'DeleteTableRow',execute:function(ftb) { Refresh.Web.TableCommands.deleteTableRow(ftb);},getValue:function(ftb) { Refresh.Web.QueryMethods.isInsideTag(ftb,'td'); }});
Refresh.Web.EditorCommands.addCommand({name:'SplitCell',execute:function(ftb) { Refresh.Web.TableCommands.splitCell(ftb);},getValue:function(ftb) { Refresh.Web.QueryMethods.isInsideTag(ftb,'td'); }});
Refresh.Web.EditorCommands.addCommand({name:'MergeCells',execute:function(ftb) { Refresh.Web.TableCommands.mergeCells(ftb);},getValue:function(ftb) { Refresh.Web.QueryMethods.isInsideTag(ftb,'td'); }});


Refresh.Web.InsertTableUtility = {

	button: null,

	ftb: null,

	container: null,

	init: function() {
		var c = document.createElement('div');
		this._container = c;
		c.id = 'InsertTablePopup';
		c.style.position = 'absolute';
		c.style.display = 'none';
		c.style.border = 'solid 1px #ccc';
		c.style.padding = '1px';
		c.style.backgroundColor = '#fff';
		document.body.appendChild(c);

		// status
		var s = document.createElement('div');
		this.status = s;
		s.setAttribute('id','InsertTablePopup_status');
		s.className = 'dropButton_Status';
		s.innerHTML = 'Insert Table';
		c.appendChild(s);

		// add main table
		var t = document.createElement('table');
		this.table = t;
		t.setAttribute('id','InsertTablePopupTable');
		t.cellPadding = 0;
		t.cellSpacing = 3;
		t.style.border = 0;
		t.style.backgroundColor = '#FAFAFA';
		t.style.fontSize = '1%';
		t.height = '100px';
		this._container.appendChild(t);

		var tb = document.createElement('tbody');
		t.appendChild(tb);
		//document.body.appendChild(t);

		for (var row=0; row<7; row++) {

			var tr = document.createElement('tr');
			tb.appendChild(tr);

			for (var col=0; col<10; col++) {
				var td = document.createElement('td');
				tr.appendChild(td);
				td.row = row;
				td.col = col;
				this.prepareCell(td);
			}
		}

		// settings
		var b = document.createElement('div');
		this.bottom = b;
		b.setAttribute('id','InsertTablePopup_button');
		b.className = 'dropButton_Bottom';
		b.innerHTML = 'Cell padding : <input type="text" style="width:50px" value="0" id="InsertTablePopup_CellPadding" /><br />Cell spacing : <input type="text" style="width:50px" value="0" id="InsertTablePopup_CellSpacing" />';
		c.appendChild(b);

		//Refresh.Utility.makeUnselectable(this._container);
	},

	show: function(ftb,button) {
		if (this._container == null) {
			this.init();
		}


		this.ftb = ftb;
		this.button = button.node;

		// position
		var targetPos = Position.positionedOffset(this.button);
		var size = Element.getDimensions(this.button);
		

		this._container.style.left = targetPos[0] + 'px';
		this._container.style.top = (targetPos[1] + size.height) + 'px';

		this._container.style.display = '';

		this.docClickListener = this._onDocClick.bindAsEventListener(this);
		Event.observe(document, "click", this.docClickListener);
		Event.observe(this.ftb._getDocument(), "click", this.docClickListener);
	},

	hide: function() {

		this._container.style.display = 'none';
	},

	_onDocClick: function(event) {

		var x = Event.pointerX(event);
		var y = Event.pointerY(event);

		//var pos = Position.positionedOffset(this.button);
		//var size = Position.getSize(this.button);

		if (!(Position.within(this._container, x, y) || Position.within(this.button, x, y))) {
			this.hide();
			Event.stopObserving(document, "click", this.docClickListener);
			Event.stopObserving(this.ftb._getDocument(), "click", this.docClickListener);
		}

	},

	_onCellOver: function(event) {
		var endTd = Event.findElement(event, 'TD');
		var cornerRow = endTd.row;
		var cornerCol = endTd.col;

		for (var row=0; row<this.table.childNodes[0].childNodes.length; row++) {
			var tr = this.table.childNodes[0].childNodes[row];

			for (var col=0; col<tr.childNodes.length; col++) {
				var td = tr.childNodes[col];

				if (row <= cornerRow && col <= cornerCol) {
					td.style.borderColor = '#FF7200';
				} else {
					td.style.borderColor = '#000000';
				}
			}
		}

		this.status.innerHTML = (cornerCol+1) + 'x' + (cornerRow+1);
	},

	_onCellClick: function(event) {
		var td = Event.findElement(event, 'TD');
		//Debugger.WriteLine('insert ' + (td.row+1) + 'x' + (td.col+1) + ' table');
		if (this.ftb) {
			Refresh.Web.TableCommands.insertTable(this.ftb, td.col+1, td.row+1, $F('InsertTablePopup_CellPadding'), $F('InsertTablePopup_CellSpacing'));
		}

		this.hide();
	},

	prepareCell: function(td) {
		td.innerHTML = '&nbsp;<br />';
		td.style.width = '12px';
		td.style.height = '12px';
		td.style.backgroundColor = '#fff';
		td.style.border = 'solid 1px #000';
		//td.style.borderWidth = '0 0 3px 3px';


		Event.observe(td, 'mouseover', this._onCellOver.bindAsEventListener(this));
		Event.observe(td, 'click', this._onCellClick.bindAsEventListener(this));
	}
};
Refresh.Web.TableCommands = {
	insertTable: function(ftb, cols, rows, cellpadding, cellspacing) {
		cols = cols || 3;
		rows = rows || 3;
		cellpadding = cellpadding || 0;
		cellspacing = cellspacing || 0;

		var doc = ftb._getDocument();
		var table = doc.createElement('table');
		table.className = 'ftb_table_helper';
		table.cellpadding = cellpadding;
		table.cellspacing = cellspacing;

		for (var i=1; i<= rows; i++) {
			var row = doc.createElement('tr');
			table.appendChild(row);
			for (var j=1; j<= cols; j++) {
				var cell = doc.createElement('td');
				cell.innerHTML = '&nbsp;';
				row.appendChild(cell);
			}
		}

		ftb.insertNodeAtSelection(table);
	},

	insertTableColumnBefore: function(ftb) {
		this.insertTableColumn(ftb, false);
	},

	insertTableColumnAfter: function(ftb) {
		this.insertTableColumn(ftb, true);
	},

	insertTableColumn: function(ftb,after) {
	   var td = ftb.getNearest("td");
	   if (!td) {
		  return;
	   }
	   var rows = td.parentNode.parentNode.rows;
	   var index = td.cellIndex;
	   for (var i = rows.length; --i >= 0;) {
		  var tr = rows[i];
		  var newTD = ftb._getDocument().createElement('td');
		  newTD.innerHTML = '<br />';

		  //if last column and insert column after is select append child
		  if (after && index==tr.cells.length-1) {
			 tr.appendChild(newTD);
		  } else {
			 var ref = tr.cells[index + ((after) ? 1 : 0)]; // 0
			 tr.insertBefore(newTD, ref);
		  }
	   }
	},

	insertTableRowBefore: function(ftb) {
		this.insertTableRow(ftb,false);
	},

	insertTableRowAfter: function(ftb) {
		this.insertTableRow(ftb,true);
	},

	insertTableRow: function(ftb,after) {
		var tr = ftb.getNearest('tr');
		if (!tr) { return; }
		var newTR = tr.cloneNode(true);
		this.clearTableRow(newTR);
		tr.parentNode.insertBefore(newTR, ((after) ? tr.nextSibling : tr));
	},

	deleteTableColumn: function(ftb) {
		var td = ftb.getNearest('td');
		if (!td) {
			return;
		}
		var index = td.cellIndex;
		if (td.parentNode.cells.length == 1) {
			return;
		}
		// set the caret first to a position that doesn't disappear
		ftb.selectNextNode(td);
		var rows = td.parentNode.parentNode.rows;
		for (var i = rows.length; --i >= 0;) {
			var tr = rows[i];
			tr.removeChild(tr.cells[index]);
		}
	},

	deleteTableRow: function(ftb) {
		var tr = ftb.getNearest('tr');
		if (!tr) {
			return;
		}
		var par = tr.parentNode;
		if (par.rows.length == 1) {
			return;
		}
		// set the caret first to a position that doesn't disappear.
		ftb.selectNextNode(tr);
		par.removeChild(tr);
	},

	clearTableRow: function(tr) {
		var tds = tr.getElementsByTagName('td');
		for (var i = tds.length; --i >= 0;) {
			var td = tds[i];
			td.rowSpan = 1;
			td.innerHTML = '<br />';
		}
	},

	splitTableRow: function(ftb,td) {
		var n = parseInt("" + td.rowSpan);
		var nc = parseInt("" + td.colSpan);
		td.rowSpan = 1;
		tr = td.parentNode;
		var itr = tr.rowIndex;
		var trs = tr.parentNode.rows;
		var index = td.cellIndex;
		while (--n > 0) {
			tr = trs[++itr];
			var otd = ftb._getDocument().createElement("td");
			otd.colSpan = td.colSpan;
			otd.innerHTML = '<br />';
			tr.insertBefore(otd, tr.cells[index]);
		}
	},

	splitTableColumn: function(td) {
		var nc = parseInt("" + td.colSpan);
		td.colSpan = 1;
		tr = td.parentNode;
		var ref = td.nextSibling;
		while (--nc > 0) {
			var otd = ftb._getDocument().createElement("td");
			otd.rowSpan = td.rowSpan;
			otd.innerHTML = '<br />';
			tr.insertBefore(otd, ref);
		}
	},

	splitTableCell: function(td) {
		var nc = parseInt("" + td.colSpan);
		splitCol(td);
		var items = td.parentNode.cells;
		var index = td.cellIndex;
		while (nc-- > 0) {
			this.splitTableRow(items[index++]);
		}
	}
};